import { Request, Response } from "express";
import { matchedData } from "express-validator";
import { decrypt } from "../../common/crypto";
import { compareSync, hashSync } from "bcryptjs";
import { responseError, responseSuccess } from "../../common/response";
import UserModel from "../../models/user/index";
import { setToken } from "../../common/token";
import { Request as RequestJWT } from "express-jwt";
import { Op } from "sequelize";

//#region 上传文件
// router.post("/upload", (req, res, next) => {
//   const form = formidable({
//     uploadDir:  path.resolve(__dirname, "../../public/upload"),
//   });
//   form.parse(req, (err, fields, files) => {
//     if (err) return next(err);
//     res.json({ fields, files });
//   });
// });

class UserController {
  //#region 用户登录
  async login(req: Request, res: Response) {
    let { username, password } = matchedData(req);
    const user = await UserModel.findOne({
      limit: 1,
      where: {
        username,
      },
    });
    if (user === null) return res.json(responseError("用户不存在"));
    const { password: sqlPassword } = user.dataValues;
    password = decrypt(password);
    if (!compareSync(password, sqlPassword!)) return res.json(responseError("密码错误"));
    if (user.status === 0) return res.json(responseError("用户已被禁用"));
    // // 生成token
    const token = setToken(username);
    res.json(responseSuccess(token, "登录成功"));
  }
  //#endregion

  //#region 用户信息
  async getUserInfo(req: RequestJWT, res: Response) {
    const header = req.auth!.header;
    const user = await UserModel.findOne({
      where: {
        username: header,
      },
      attributes: {
        exclude: ["password"],
      },
    });
    if (user === null) return res.json(responseError("用户不存在"));
    res.json(responseSuccess(user));
  }
  //#endregion

  //#region 用户列表
  async getUserList(req: Request, res: Response) {
    const { page, pageSize, keyword } = req.query;
    const offset = (Number(page) - 1) * Number(pageSize);
    const size = Number(pageSize);
    const { count, rows } = await UserModel.findAndCountAll({
      offset: offset,
      limit: size,
      where: {
        auth: {
          [Op.ne]: 0,
        },
        [Op.or]: [
          {
            phone: {
              [Op.like]: `%${keyword}%`,
            },
          },
          {
            name: {
              [Op.like]: `%${keyword}%`,
            },
          },
          {
            username: {
              [Op.like]: `%${keyword}%`,
            },
          },
        ],
      },
      attributes: {
        exclude: ["password"],
      },
    });
    const data = {
      total: count,
      data: rows,
      page: Number(page),
      pageSize: Number(pageSize),
    };
    res.json(responseSuccess(data));
  }
  //#endregion

  //#region 添加用户
  async addUser(req: Request, res: Response) {
    const body = req.body;
    const [created] = await UserModel.findOrCreate({
      where: {
        username: body.username,
      },
      defaults: {
        ...body,
        password: hashSync(decrypt(body.password), 10),
        role: "",
        auth: 1,
      },
    });

    if (!created) return res.json(responseError("用户已存在"));
    res.json(responseSuccess("添加成功"));
  }
  //#endregion

  //#region 删除用户
  async deleteUser(req: Request, res: Response) {
    const { id } = req.body;
    const rows = await UserModel.destroy({
      where: {
        id: id,
      },
    });
    if (rows === 1) return res.json(responseSuccess("删除成功"));
    res.json(responseSuccess("删除失败"));
  }
  //#endregion

  //#region 初始化密码
  async resetPassword(req: Request, res: Response) {
    const { id } = req.body;
    const rows = await UserModel.update(
      {
        password: hashSync("123456", 10),
      },
      {
        where: {
          id: id,
        },
      },
    );
    if (rows[0] === 1) return res.json(responseSuccess("初始化密码成功"));
    res.json(responseSuccess("初始化密码失败"));
  }
  //#endregion

  //#region 初始化密码
  async changeUserStatus(req: Request, res: Response) {
    const { status, id } = req.body;
    const rows = await UserModel.update(
      {
        status: status,
      },
      {
        where: {
          id: id,
        },
      },
    );
    if (rows[0] === 1) return res.json(responseSuccess("修改状态成功"));
    res.json(responseSuccess("修改状态失败"));
  }
  //#endregion

  //#region 修改用户信息
  async changeUserInfo(req: Request, res: Response) {
    const { id } = req.body;
    const rows = await UserModel.update(req.body, {
      where: {
        id: id,
      },
    });
    if (rows[0] === 1) return res.json(responseSuccess("修改成功"));
    res.json(responseSuccess("修改失败"));
  }
  //#endregion

  //#region 修改密码
  async changePassword(req: RequestJWT, res: Response) {
    let { password, newPassword } = matchedData(req);
    const header = req.auth!.header;
    const user = await UserModel.findOne({
      where: {
        username: header,
      },
    });
    if (user === null) return res.json(responseError("用户不存在"));
    const { password: sqlPassword } = user;
    password = decrypt(password);
    newPassword = decrypt(newPassword);
    // !compareSync(password, sqlPassword!)
    if (!compareSync(password, sqlPassword!)) return res.json(responseError("密码错误"));
    if (compareSync(password, newPassword)) return res.json(responseError("新密码不能与旧密码相同"));
    const rows = await UserModel.update(
      {
        password: hashSync(newPassword, 10),
      },
      {
        where: {
          id: user.id,
        },
      },
    );
    if (rows[0] === 1) return res.json(responseSuccess("修改成功"));
  }
  //#endregion
}

export default UserController;
